package com.skyline.energy.transaction;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import com.skyline.energy.annotation.Transaction;
import com.skyline.energy.utils.CommonUtils;


public class TransactionDefinition {
	private IsolationLevel isolationLevel;
	private boolean readOnly;
	private Class<? extends Throwable> rollback;
	private boolean needTransaction;

	public TransactionDefinition(Object target, Method actualMethod) {
		Annotation annotation = actualMethod.getAnnotation(Transaction.class);
		Transaction tx = (Transaction) annotation;
		if(tx != null) {
			this.isolationLevel = tx.isolation();
			this.readOnly = tx.readonly();
			this.rollback = tx.rollback();
			needTransaction = true;
		} else {
			needTransaction = false;
		}
	}

	public IsolationLevel getIsolationLevel() {
		return isolationLevel;
	}

	public boolean isReadOnly() {
		return readOnly;
	}

	public boolean rollbackOn(Throwable ex) {
		CommonUtils.assertNotNull(ex, "回滚抛出异常不能为空");
		Class<? extends Throwable> cls = ex.getClass();
		if (cls.equals(rollback)) {
            return true;
        }
		return rollback.isAssignableFrom(cls);
	}

	public boolean isNeedTransaction() {
		return needTransaction;
	}
	
}
